import { Component, Input } from '@angular/core'
import { Widget } from '../../model'
import { JsonApiService } from '../../../../core/api/json-api.service'

declare var echarts: any

let chart = null
let timer = null

// 数据分类
const filData = {
  linkNum: {
    name: '在线数',
    data: [],
    rowData: []
  },
  currentInBytes: {
    name: '当前进站',
    data: [],
    rowData: []
  },
  currentOutBytes: {
    name: '当前出站',
    data: [],
    rowData: []
  },
}

@Component({
  selector: 'traffic-echarts-mins',
  templateUrl: './traffic-echarts-mins.html',
  styleUrls: ['./traffic-echarts-mins.css']
})

export class TrafficEchartsMins implements Widget {
  @Input() componentData: any

  totalInNum = '0B'// 总进站
  totalOutNum = '0B' // 总出战
  loading = false

  chartOption = {
    title: { show: false },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross' //十字星	
      },
      formatter: function (params) {
        let res = '';
        const len = params.length;
        const dataIndex = params[0].dataIndex;
        for (let i = 0; i < len; i++) {
          for (let item in filData) {
            if (params[i].seriesName == filData[item].name) {
              let val = filData[item].data[dataIndex];
              if (params[i].seriesName !== '在线数') {
                val = val + 'KB';
                res = res + params[i].marker + params[i].seriesName + ':' + val + '</br>'
              } else {
                res = res + params[i].name + '</br>' + params[i].marker + params[i].seriesName + ':' + val + '</br>'
              }
            }
          }
        }
        return res;
      }
    },
    grid: {
      top: '12',
      left: '22',
      right: '32',
      bottom: '22',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [],
    },
    yAxis: [{
      show: true,
      name: '在线数',
      type: 'value',
      position: 'left',
      axisLine: {
        lineStyle: {
          color: 'gray'
        }
      },
      axisLabel: {
        formatter: '{value} '
      }
    }],
    series: []
  };
  constructor(private jsonApiService: JsonApiService) { }

  initChart() {
    this.loading = true
    this.jsonApiService.http2("control/station/traffic/minute/trafficStatisticsForMinute.html", 'type=0').subscribe(result => {
      this.loading = false
      const len = result.data.length;
      if (len < 2) {
        return;
      }
      // 最后一位数据即为总数据
      this.totalInNum = getFlowUnit(result.data[len - 1].totalInBytes);
      this.totalOutNum = getFlowUnit(result.data[len - 1].totalOutBytes);
      const xAxisArr = this.chartOption.xAxis.data; //X时间轴
      // 遍历数据
      for (let i = 0; i < len; i++) {
        // 横轴数据
        xAxisArr.push(result.data[i].createTime);
        for (let item in filData) {
          filData[item].rowData.push(result.data[i][item]);
          if (item == 'linkNum') {
            filData[item].data.push(result.data[i][item]);
          } else {
            let value = result.data[i][item];
            value = common.twoDecimal(value / 1024); //单位kb
            filData[item].data.push(value);
          }
        }
      }
      const brokenLineArr = []; //所有的折线数据
      for (let item in filData) {
        if (filData[item].data.length > 1) {
          const obj = {
            name: filData[item].name,
            type: 'line',
            borderWidth: 5,
            data: filData[item].data,
          }
          brokenLineArr.push(obj);
        }
      }
      this.chartOption.series = brokenLineArr
      this.setOptions(this.chartOption)
      this.setTimer()
    })
  }

  ngAfterViewInit() {
    setTimeout(() => {
      chart = echarts.init(document.getElementById('flow-chart'))
      this.setOptions(this.chartOption)
      this.initChart()
      window.addEventListener('resize', this.resizeChart)
    }, 0);
  }

  ngOnDestroy() {
    if (!chart) return
    if (timer) {
      clearInterval(timer)
      timer = null
    }
    window.removeEventListener('resize', this.resizeChart)
    chart.dispose()
    chart = null
  }

  resizeChart() {
    chart && chart.resize()
  }

  setOptions(option: any) {
    if (chart) {
      chart.setOption(option)
    }
  }

  setTimer() {
    const that = this;
    const timingData = function () {
      //定时获取数据函数
      that.jsonApiService.http2("control/station/traffic/minute/trafficStatisticsForMinute.html", 'type=1').subscribe(result => {
        that.totalInNum = getFlowUnit(result.data.totalInBytes);
        that.totalOutNum = getFlowUnit(result.data.totalOutBytes);
        that.chartOption.xAxis.data.push(result.data.createTime);
        for (let item in filData) {
          filData[item].rowData.push(result.data[item]);
          if (item == 'linkNum') {
            filData[item].data.push(result.data[item]);
          } else {
            var value = result.data[item];
            value = common.twoDecimal(value / 1024); //单位kb
            filData[item].data.push(value);
          }
        }
        that.setOptions(that.chartOption);
      })
    }
    timer = setInterval(timingData, 10000);

  }
}


//获得流量单位,B,KB,MB,GB
function getFlowUnit(value) {
  var result = '0 B';
  if (value < 1024) {
    result = value + 'B';
  }
  if (value >= 1024 && value < 1024 * 1024) {
    //单位kb
    value = common.twoDecimal(value / 1024);
    result = value + 'KB';
  }
  if (value >= 1024 * 1024 && value < 1024 * 1024 * 1024) {
    //单位Mb
    value = common.twoDecimal(value / 1024 / 1024);
    result = value + 'MB';
  }
  if (value >= 1024 * 1024 * 1024) {
    //单位GB
    value = common.twoDecimal(value / 1024 / 1024 / 1024);
    result = value + 'GB';
  }

  return result;
}